package study.io.springboot.upload.controller;

import cn.hutool.core.util.RandomUtil;
import com.google.common.base.Stopwatch;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import study.eggs.result.Result;
import study.eggs.result.Results;
import study.io.springboot.upload.support.utils.CopyUtils;
import study.io.springboot.upload.support.utils.URLUtils;

import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/copy")
public class _4_CopyController {

    @RequestMapping("/copy")
    public Result copy_url(@RequestBody Request request) {
        List<String> urlLt = request.getUrlLt();
        String dest = request.getDest();
        //
        Stopwatch stopwatch = Stopwatch.createStarted();
        List<URL> myUrlLt = URLUtils.toURLs(urlLt);
        myUrlLt.stream().forEach(e -> {
            Stopwatch s = Stopwatch.createStarted();
            CopyUtils.zeroCopyURLToFile(e, dest + RandomUtil.randomInt() + ".pdf");
            log.info(">>>>>>>>>> {} sec", s.elapsed(TimeUnit.SECONDS));
        });
        log.info("total cost time: {} sec", stopwatch.elapsed(TimeUnit.SECONDS));

        return Results.ok();
    }

    @RequestMapping("/zeroCopy")
    public Result copy_disk(@RequestBody Request request) {
        String src = request.getSrc();
        String dest = request.getDest();

        //
        Stopwatch stopwatch = Stopwatch.createStarted();
        CopyUtils.copy(src, dest);
        log.info("total cost time: {} sec", stopwatch.elapsed(TimeUnit.SECONDS));
        return Results.ok();
    }

    @Data
    public class Request {
        private List<String> urlLt;
        private String src;
        private String dest;
    }
}
